Thread: [question]unsigned number with negative value?

  1. #1
    Registered User
    Join Date
    Dec 2009
    Posts
    16

    Question [question]unsigned number with negative value?

    Hi everyone,

    I am confused about the definition of the unsigned. Could anyone please help to explain the result of running a simple test code. As below.

    Code:
    void main()
     {
      unsigned long num_a = 4;
      unsigned long num_b = 8;
      unsigned long num_c;
      unsigned long num_d = 1;
      
      num_c = num_a-num_b;
      num_d -= num_c;
      printf(" num_c = num_a - num_b, num_c is: %ld num_d is:%ld" , num_c, num_d);    
    }
    The result is: num_c = num_a - num_b, num_c is: -4 num_d is:5

    I thought num_c is declared as an unsigned long but it can actually present a negative number. I guess I don't have the correct understanding of the unsigned number.

    question 1. for "num_c = num_a-num_b", (num_c = 4-8), can num_c, an unsigned long integer, carry a negative value? why?

    question 2. for "num_d -= num_c;" num_c has a unsigned long type, but is assigned to a negative number as the result of the arithmetic, would any potential side effect be introduced if continue to use num_c in the function?
    Last edited by learn; 12-26-2009 at 12:06 AM.

  2. #2
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Unsigned and signed integers have the same representation. You are using %ld, which is a signed decimal format specifier. Therefore, the bit pattern of the integer is printed in signed form. Whether the variable itself is signed or not doesn't have any effect. Some compilers will warn you when you make such a mistake. Obviously, in this case, it did not.

    If you intend to print an unsigned integer, you should use %lu, not %ld.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  3. #3
    Registered User
    Join Date
    Dec 2009
    Posts
    16
    Many thanks. :-)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Convert bytes to int, keep the negative number
    By umm in forum C Programming
    Replies: 7
    Last Post: 03-20-2009, 04:47 PM
  2. scanf oddities
    By robwhit in forum C Programming
    Replies: 5
    Last Post: 09-22-2007, 01:03 AM
  3. How can i convert negative number to positive number ?
    By winsonlee in forum C Programming
    Replies: 2
    Last Post: 05-05-2004, 08:02 AM
  4. parsing a number
    By juancardenas in forum C Programming
    Replies: 1
    Last Post: 02-19-2003, 01:10 PM
  5. Random Number problem in number guessing game...
    By -leech- in forum Windows Programming
    Replies: 8
    Last Post: 01-15-2002, 05:00 PM